/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cardsender_service.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "file_ex.h"
#include "system_ability_definition.h"
#include "hilog_wrapper.h"
#include "cardsender_errors.h"
#include "cardsender_common.h"
#include "devmgr.h"

using namespace std;
using namespace OHOS;

namespace SwanLink {
namespace Finance {
namespace {
auto pms = ::SwanLink::Finance::DelayedSpSingleton<::SwanLink::Finance::CardsenderService>::GetInstance();
const bool G_REGISTER_RESULT = OHOS::SystemAbility::MakeAndRegisterAbility(
    pms.GetRefPtr());
}

CardsenderService::CardsenderService(): SystemAbility(OHOS::FINANCE_CARDSENDER_SERVICE_ID, true),
    ready(false),
    m_pFdHandler(new FdHandler()),
    m_pPlgMgr(new PluginManager()),
    m_iStatus(NOT_INIT) {
}

CardsenderService::~CardsenderService()
{
    if (nullptr != m_pFdHandler) {
      delete m_pFdHandler;
    }
    if (nullptr != m_pPlgMgr) {
      delete m_pPlgMgr;
    }
}

void CardsenderService::OnDump() {}

void CardsenderService::OnStart()
{
    CARDSENDER_HILOGD(CARDSENDER_SRV, "Enter");
    if (ready) {
        CARDSENDER_HILOGD(CARDSENDER_SRV, "Service is ready, nothing to do");
        return;
    }
    if (!(Init())) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "Call init failed");
        return;
    }

    if (!Publish(this)) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "Register to system ability manager failed");
        return;
    }
    ready = true;
}

bool CardsenderService::Init()
{
    CARDSENDER_HILOGD(CARDSENDER_SRV, "Enter");
    OnInit(CASH_DEVICE_CARDSENDER, "CardSender");
    CARDSENDER_HILOGI(CARDSENDER_SRV, "Success");
    return true;
}

void CardsenderService::OnStop()
{
    CARDSENDER_HILOGW(CARDSENDER_SRV, "Enter");
    OnFree();
    CARDSENDER_HILOGW(CARDSENDER_SRV, "Success");
}

int32_t CardsenderService::Dump(int32_t fd, const std::vector<std::u16string>& args)
{
    return SUCCESS;
}

std::vector<DevAccess> CardsenderService::GetSupportAccess()
{
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::GetSupportAccess enter");
    std::vector<DevAccess> result;
    char node[][MAX_DEV_NAME_LEN] = { "COM", "USB" };

    if (m_pPlgMgr == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "Plugin not loaded!");
        return result;
    }
    for (size_t i = 0; i < (sizeof(node) / sizeof(node[0])); i++) {
        int k = 0;
        do {
            char com[MAX_DEV_NAME_LEN];
            sprintf_s(com, MAX_DEV_NAME_LEN, "%s%d", node[i], ++k);
            std::string name;
            std::string dev;
            int mode;
            //  读取所有节点信息的设备名称、设备通信方式
            if (!DevMgr::GetDevConfig(com, name, dev, mode)) {
                m_iStatus = ERR_CONFIG_LOAD_FAILED;
                break;
            }
            DevAccess access;
            //  根据设备名获取对应设备名插件的接入参数
            if (!m_pPlgMgr->GetAccess(name, (ACCESS_MODE)mode, dev, access)) {
                CARDSENDER_HILOGW(CARDSENDER_SRV,
                                  "get access failed,name = %{public}s,dev = %{public}s,mode = %{public}d",
                                  name.c_str(), dev.c_str(), (int)mode);
                continue;
            }
            CARDSENDER_HILOGW(CARDSENDER_SRV,
                "get access success, name = %{public}s, desc = %{public}s, dev = %{public}s, mode = %{public}d",
                access.name, access.desc, access.transport.dev, access.transport.mode);
            result.push_back(access);
        } while (true);
    }
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::GetSupportAccess out");
    return result;
}

int CardsenderService::Open(const std::string& name, const Transport& trans)
{
    CARDSENDER_HILOGD(CARDSENDER_SRV,
                      "CardsenderService::Open enter,name %{public}s,mode %{public}d",
                      name.c_str(), trans.mode);
    if (m_pFdHandler->IsTakeUp(trans.dev)) {
        CARDSENDER_HILOGD(CARDSENDER_SRV, "Port is taken up");
        // 如果关闭了应重新打开
        int fd = m_pFdHandler->GetFd(trans.dev);
        std::shared_ptr<IAdaptor> adaptor = m_pFdHandler->GetAdaptor(fd);
        if (!adaptor->IsOpen()) {
            m_iStatus = adaptor->Open(trans);
            if (m_iStatus != SUCCESS) {
                CARDSENDER_HILOGD(CARDSENDER_SRV, "Remove Adaptor from FdHandler");
                m_pFdHandler->DelFd(fd);
                return m_iStatus;
            }
            return fd;
        }
        m_iStatus = SUCCESS;
        return fd;
    }

    std::shared_ptr<IAdaptor> adaptor = m_pPlgMgr->CreateAdaptor(name);
    if (adaptor == nullptr) {
        return m_pPlgMgr->GetStatus(name);
    }

    CARDSENDER_HILOGD(CARDSENDER_SRV, "Open device %{public}s", trans.dev);
    m_iStatus = adaptor->Open(trans);
    if (m_iStatus != SUCCESS) {
        CARDSENDER_HILOGD(CARDSENDER_SRV, "Open failed, status = %{public}d", m_iStatus);
        return m_iStatus;
    }
    CARDSENDER_HILOGD(CARDSENDER_SRV, "Add Adaptor to FdHandler");
    return m_pFdHandler->AddFd(trans.dev, adaptor);
}

int CardsenderService::Close(int handle)
{
    CARDSENDER_HILOGD(CARDSENDER_SRV, "CardsenderService::Close enter ");
    std::shared_ptr<IAdaptor> adaptor = m_pFdHandler->GetAdaptor(handle);
    if (adaptor == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "句柄无效");
        m_iStatus = HANDLE_INVALID;
        return m_iStatus;
    }
    CARDSENDER_HILOGD(CARDSENDER_SRV, "Close device");
    m_iStatus = adaptor->Close();

    if (adaptor->IsOpen()) {
        return m_iStatus;
    }
    // 关闭的状态码
    CARDSENDER_HILOGD(CARDSENDER_SRV, "Remove Adaptor from FdHandler");
    m_pFdHandler->DelFd(handle);
    return m_iStatus;
}

int CardsenderService::Reset(int handle)
{
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::reset enter ");
    std::shared_ptr<IAdaptor> adaptor = m_pFdHandler->GetAdaptor(handle);
    if (adaptor == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "句柄无效");
        m_iStatus = HANDLE_INVALID;
        return m_iStatus;
    }
    m_iStatus = SUCCESS;
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::reset out ");
    return adaptor->Reset();
}

void CardsenderService::OnInit(int devId, const std::string &attr)
{
    m_pFdHandler->SetBaseId(devId);
    m_pPlgMgr->LoadAllPlugin(attr);
}

void CardsenderService::OnFree()
{
    m_pPlgMgr->FreeAllPlugin();
}

std::shared_ptr<IAdaptor> CardsenderService::GetAdaptor(int handle)
{
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::GetAdaptor enter ");
    if (m_pFdHandler == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "句柄未初始化");
        m_iStatus = NOT_INIT;
        return nullptr;
    }
    std::shared_ptr<IAdaptor> adaptor = m_pFdHandler->GetAdaptor(handle);
    if (adaptor == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "句柄未找到");
        m_iStatus = HANDLE_INVALID;
    }
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::GetAdaptor out ");
    return adaptor;
}

int CardsenderService::DispenseCard(int handle)
{
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::DispenseCard enter ");
    std::shared_ptr<ICardSenderAdaptor> adaptor = static_pointer_cast<ICardSenderAdaptor>(
        m_pFdHandler->GetAdaptor(handle));
    if (adaptor == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "句柄无效");
        m_iStatus = HANDLE_INVALID;
        return m_iStatus;
    }
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::DispenseCard out ");
    return adaptor->DispenseCard();
}

int CardsenderService::QueryStatus(int handle, int *suppBinStat, int *retainBinStat)
{
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::QueryStatus enter");
    std::shared_ptr<ICardSenderAdaptor> adaptor = static_pointer_cast<ICardSenderAdaptor>(
        m_pFdHandler->GetAdaptor(handle));
    if (adaptor == nullptr) {
        CARDSENDER_HILOGE(CARDSENDER_SRV, "句柄无效");
        m_iStatus = HANDLE_INVALID;
        return m_iStatus;
    }
    m_iStatus = SUCCESS;
    unsigned char byteSuppBinStat;
    unsigned char byteRetainBinStat;
    CARDSENDER_HILOGI(CARDSENDER_SRV, "CardsenderService::QueryStatus out");
    int ret = adaptor->GetStatus(&byteSuppBinStat, &byteRetainBinStat);
    *suppBinStat = byteSuppBinStat;
    *retainBinStat = byteRetainBinStat;
    return ret;
}
}  //  namespace Finance
}  //  namespace SwanLink
